//
//  HMUserAccountViewModel.swift
//  微博
//
//  Created by 郭鉴增 on 2016/12/9.
//  Copyright © 2016年 郭鉴增. All rights reserved.
//

import UIKit
//OAuth登录页面的网络请求的封装
class HMUserAccountViewModel: NSObject {

    //单列全区访问点
    static let sharedUserAccount: HMUserAccountViewModel = HMUserAccountViewModel()
    
    //用户账号模型
    var userAccount: HMUserAccount? {
        return HMUserAccount.loadUserAccount()
    }
    //判断是否登陆的标记
    var isLogin: Bool {
        return accessTOken != nil
    }
    
    //获取accesstoken的逻辑
    //1.判断accesstoken是否为nil,如果为nil.直接返回nil
    //2.如果不为nil,判断accessToken过期时间是否大于我们的当前时间,如果大于我们的当前时间表示没有过期,返回accesstoken,否则,表示过期了,那么返回nil
    var accessTOken: String? {
        guard let token = userAccount?.access_token else{
            return nil
        }
        //代码执行动词,表示token不为nil
        
        if userAccount?.expiresDate?.compare(Date()) == ComparisonResult.orderedDescending {
            //没过期
            return token
        }else{
            //过期了
            return nil
        }
    }
    
    
    //通过code获取accesstoken
    func requestAccessToken(code: String, callBack: @escaping (Bool)->()) {
        HMNetworkTools.sharedTools.requestAccesstoken(code: code) { (response, error) in
            if error != nil{
                print(error!)
                callBack(false)
                return
            }
            //代码执行到此,表示请求成功
            print(response)
            
            let dic = response as! [String: Any]
            //把字典转成模型
            let userAccount = HMUserAccount(dic:dic)
            //获取到用户id以后,获取对应的用户信息
            self.requestUserInfo(userAccount: userAccount, callBack: callBack)
        }
    }
    
    //通过用户id和accesstoken获取用户信息
    private func requestUserInfo(userAccount:HMUserAccount, callBack: @escaping (Bool)->()) {
        
        let accessToken = userAccount.access_token!
        let userId = userAccount.uid
        
        HMNetworkTools.sharedTools.requestUserInfo(accessToken: accessToken, uid: userId, callBack: {(response, error) -> () in
            
            if error != nil{
                print(error!)
                callBack(false)
                return
            }
            //代码执行到此,表示请求成功
            print(response)
            
            let dic = response as! [String: Any]
            let name = dic["name"]
            let avatar_large = dic["avatar_large"]
            //给对象里的属性赋值
            userAccount.name = name as? String
            userAccount.avatar_large = avatar_large as? String
            
            //登录成功了,需要归档属性
            userAccount.saveUserAccount()
            
            //代码执行到此,表示请求成功
            callBack(true)
        })
    }

}
